const chalk = require('chalk');
const fs = require("fs");
const JSZip = require('jszip');
const argv = require('minimist')(process.argv.slice(2));
const cwd = process.cwd();
const readdir = function () {
    return fs.readdirSync(cwd).filter(function (it) { return it.endsWith('.jar') || it.endsWith('.aar') })
};

const printTree = async function () {
    const files = readdir();
    const treeObj = {};
    await Promise.all(files.map(async function (it) {
        if (it.endsWith('.jar')) {
            treeObj[it] = {};
        } else {
            const buffer = fs.readFileSync(cwd + '/' + it);
            const data = await JSZip.loadAsync(buffer);
            const tree = Object.keys(data.files).filter(function (it) { return it.startsWith('libs/') && it !== 'libs/' });
            if (tree.length > 0) {
                treeObj[it] = tree;
            }
        }
    }));
    if (Object.keys(treeObj).length === 0) {
        console.log('未检测到任何模块');
        return
    }
    let printStr = JSON.stringify(treeObj, null, '\t');
    if (argv.key) {
        argv.key.split(',').forEach(function (it) {
            printStr = printStr.replace(new RegExp(it), chalk.red(it));
        });
    }
    console.log(printStr);
};
printTree();
